package com.two.screen.water.balance.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.jakewharton.rxbinding2.view.RxView
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.database.OrderDBDao
import com.two.screen.water.balance.bean.database.OrderProductDB
import com.two.screen.water.balance.listener.MyObserver
import com.two.screen.water.balance.net.api.OrderApi
import com.two.screen.water.balance.print.PrinterAll
import com.two.screen.water.balance.print.bean.PrintConnectSaleReportBean
import com.two.screen.water.balance.print.bean.PrintProductBean
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.utils.ARouterUtils
import com.two.screen.water.balance.utils.CommUtils
import com.two.screen.water.balance.utils.RxUtils
import com.two.screen.water.balance.utils.isNotAvailable
import com.two.screen.water.balance.widget.DividerItemDecoration
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import kotlinx.android.synthetic.main.activity_index.*
import kotlinx.android.synthetic.main.activity_jiao_jie_list.*
import java.util.concurrent.TimeUnit

@Route(path = ARouterUtils.JiaoJieProductListActivity)
class JiaoJieProductListActivity : BaseActivity() {
    override fun getContentLayout(): Any = R.layout.activity_jiao_jie_list
    @Autowired @JvmField var mUpdateTime: String? = null
    @Autowired @JvmField var mUserId: String? = null
    @Autowired @JvmField var mUserName: String? = null

    lateinit var mProductAdapter: ProductAdapter

    override fun initView(savedInstanceState: Bundle?) {
        ARouter.getInstance().inject(this)
        d("mUpdateTime:$mUpdateTime,mUserId:$mUserId")
    }

    override fun initData() {
        initRecyclerView()
        getUserData()
    }

    private fun initRecyclerView() {
        (mCommonRecyclerView?.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mHadChooseRecyclerView?.addItemDecoration(
            DividerItemDecoration(
                this, DividerItemDecoration.HORIZONTAL_LIST,
                resources.getDimension(R.dimen.common_measure_1dp).toInt(), ContextCompat.getColor(App.context!!, R.color.line_color)
            )
        )
        mProductAdapter = ProductAdapter()
        mCommonRecyclerView?.layoutManager = LinearLayoutManager(this)
        mCommonRecyclerView?.adapter = mProductAdapter
        mProductAdapter.bindToRecyclerView(mCommonRecyclerView)
        mProductAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty1)
    }

    private fun getUserData() {
        Observable.create(ObservableOnSubscribe<MutableList<OrderProductDB>> { e ->
            //查出本账号的交接订单
            val list = App.mDaoSession?.orderDBDao?.queryBuilder()
                //TODO:这里还需要过滤掉 挂单
                ?.where(OrderDBDao.Properties.OrderType.eq(OrderApi.ORDER_TYPE_NORMAL))
                ?.where(OrderDBDao.Properties.UserId.eq(mUserId))
                ?.where(OrderDBDao.Properties.CreateTime.ge(mUpdateTime))//大于登录时间
                //?.where(WhereCondition.StringCondition(""))
                ?.list()

            //拿到交接订单的商品
            var goodList: MutableList<OrderProductDB> = mutableListOf()
            list?.forEach {
                it.orderProductDBList?.forEach { product ->
                    goodList.add(product)
                }
            }

            //把商品进行分组
            val groupingByGoodList = goodList.groupBy { it.productName.plus("<==>").plus(it.productId) }
            //统计他的总量
            var newGoodList: MutableList<OrderProductDB> = mutableListOf()
            groupingByGoodList.forEach { map ->
                //map.key
                if (map.value.isNotEmpty()) {
                    var orderProductDB = CommUtils.gson.fromJson(CommUtils.gson.toJson(map.value.first()), OrderProductDB::class.java)
                    var weight = 0.0
                    var subTotalPrice = 0.0
                    map.value.forEach {
                        weight += orderProductDB.weight.toDouble()
                        subTotalPrice += orderProductDB.subTotalPrice.toDouble()
                    }
                    orderProductDB.weight = String.format("%.3f", weight)
                    orderProductDB.subTotalPrice = String.format("%.2f", subTotalPrice)
                    newGoodList.add(orderProductDB)
                }
            }
            if (newGoodList.isNotEmpty()) e.onNext(newGoodList) else e.onError(Throwable("找不到商品"))
        })
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(this@JiaoJieProductListActivity))
            .subscribe(object : MyObserver<MutableList<OrderProductDB>>() {
                @SuppressLint("SetTextI18n", "CheckResult")
                override fun onNext(list: MutableList<OrderProductDB>) {
                    mProductAdapter.setNewData(list)
                    var totalWeight = 0.0
                    var totalPrice = 0.0
                    list.forEach {
                        totalPrice += it.subTotalPrice.toDouble()
                        totalWeight += it.weight.toDouble()
                    }
                    mTotalTv.text = "总数量：${String.format("%.3f", totalWeight)}，总价：${String.format("%.2f", totalPrice)}元"

                    mPrintTv.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE
                    RxView.clicks(mPrintTv)
                        .throttleFirst(1, TimeUnit.SECONDS)
                        .subscribe {
                            PrinterAll.printConnectSaleReport(PrintConnectSaleReportBean().apply {
                                this.title = "销售商品报表"
                                this.operationName = mUserName
                                this.startTime = CommUtils.toYMD_HMS(mUpdateTime?.toLong())
                                this.endTime = CommUtils.toYMD_HMS(System.currentTimeMillis() / 1000)
                                this.total = mTotalTv.text.toString()
                                this.productList = list.map {
                                    PrintProductBean().apply {
                                        this.name = it.productName
                                        this.price = it.realPrice
                                        this.weight = it.weight
                                        this.subPrice = it.subTotalPrice
                                    }
                                }.toMutableList()
                            })
                        }
                }
            })
    }

    /*商品列表 适配器*/
    inner class ProductAdapter : BaseQuickAdapter<OrderProductDB, BaseViewHolder>(R.layout.item_jiao_jie_product, null) {
        @SuppressLint("CheckResult", "NotifyDataSetChanged")
        override fun convert(helper: BaseViewHolder, item: OrderProductDB) {
            helper
                .setText(R.id.item_tv1, (helper.bindingAdapterPosition + 1).toString())
                .setText(R.id.item_tv2, item.productName.isNotAvailable())
                .setText(R.id.item_tv3, item.oriPrice.isNotAvailable().plus("元/").plus(item.unitName))
                .setText(R.id.item_tv4, item.cateName.isNotAvailable())
                .setText(R.id.item_tv5, item.weight.isNotAvailable())
                .setText(R.id.item_tv6, item.subTotalPrice.isNotAvailable())
        }
    }

    @SuppressLint("ClickableViewAccessibility", "CheckResult")
    override fun initListener() {
        mGoBackLayout.setOnClickListener { goBack() }
    }

}